package com.xrit.sunnyday.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.xrit.sunnyday.dao.OrderSettingDao;
import com.xrit.sunnyday.exception.SunnydayException;
import com.xrit.sunnyday.pojo.OrderSetting;
import com.xrit.sunnyday.service.OrderSettingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 类名称: OrderSettingServiceImpl
 * 类描述:TODO
 * 创建人: czb
 * 创建时间:2022/6/21 上午 10:30
 * Version 1.0.0
 */
@Service(interfaceClass = OrderSettingService.class)
@Transactional
public class OrderSettingServiceImpl implements OrderSettingService {

    @Autowired
  private   OrderSettingDao orderSettingDao;
    /*批量导入*/
    @Override
    public void add(ArrayList<OrderSetting> orderSettingList) throws SunnydayException {
        //1.遍历，挨个取出每一行(OrderSetting)
        for (OrderSetting os : orderSettingList) {
            //2.取出日期
            Date orderDate = os.getOrderDate();
            /**
             * 3.拿日期查询数据表里边是否存在重复，如果重复代表医生现在要进行更新
             * 逻辑：
             * 存在
             * 判断数据库表中已预约人数是否大于 要更新的 可预约人数
             *  大于 则报错
             *  小于 则更新可预约数
             * 不存在
             *  则插入预约设置
             */
         OrderSetting osInDb= orderSettingDao.findByOrderDate(orderDate);
            //判断对应的日期是否存在(excel中一行对应一个OrderSetting实体)
         if (null!=osInDb){
             //判断数据库表中已预约人数是否大于 要更新的 可预约人数,反之抛异常
            if (osInDb.getReservations()>os.getNumber()){
                throw new SunnydayException(os.getOrderDate()+"中，已预约的人数比你现在设置的可预约人数要大");
            }
            orderSettingDao.updateNumber(os);
         }else {//不存在
             orderSettingDao.add(os);
         }

        }
    }

    /*查询预约的信息*/
    @Override
    public List<Map<String, Integer>> getDataByMonth(String month) {
        String date = month+"-01";
        return orderSettingDao.getDataByMonth(date);
    }

    /*设置预约信息*/
    @Override
    public void editNumberByDate(OrderSetting orderSetting) {
        OrderSetting osInDb = orderSettingDao.findByOrderDate(orderSetting.getOrderDate());
        if (null!=osInDb){
            if (osInDb.getReservations()>orderSetting.getNumber()){
                throw new SunnydayException("最大预约人数不能小已预约人数！");
            }
            orderSettingDao.editNumberByOrderDate(orderSetting);
        }else {
            orderSettingDao.add(orderSetting);
        }
    }
}
